/*
 * 	Flan.Zeng 2011-2016	http://git.oschina.net/signup?inviter=flan
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.flan.stock.utils;

import java.io.File;

import android.content.Context;
import android.os.Environment;

/**
 * 网络图片的文件缓存对象
 * @author flan
 * @date   2015年11月12日
 */
public class FileCache {
	
	private File cacheDir;

	public FileCache(Context context) {
		super();
		
		//如果有SD卡则在SD卡中建一个LazyList的目录存放缓存的图片 没有SD卡就放在系统的缓存目录中
		if(Environment.getExternalStorageDirectory().equals(Environment.MEDIA_MOUNTED)){
			cacheDir = new File(Environment.getExternalStorageDirectory(),"ImageCache");
		}else {
			cacheDir = context.getCacheDir();
		}
		
		if(!cacheDir.exists()){
			cacheDir.mkdirs();
		}
	}
	
	/**
	 * 给定网络图片的URL查找磁盘中的图片文件
	 * @param imgUrl
	 * @return
	 */
	public File getFile(String imgUrl){
		
		//将url的hashCode作为缓存的文件名
		String fileName = String.valueOf(imgUrl.hashCode());
		File file = new File(cacheDir, fileName);
		
		return file;
	}
	
	/**
	 * 清楚缓存的图片文件
	 */
	public void clear(){
		
		File[] files = cacheDir.listFiles();
		if(files == null){
			return;
		}else {
			for(File f : files){
				f.delete();
			}
		}
	}
}
